package com.hsytech.dijiebao.person.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.VolleyError;
import com.deparse.dpframe.utils.DPHttpUtil;
import com.deparse.dpframe.utils.DPLogUtil;
import com.hsytech.dijiebao.R;
import com.hsytech.dijiebao.base.BaseActivity;
import com.hsytech.dijiebao.bean.SeeCityBean;
import com.hsytech.dijiebao.person.SeeCityAdapter;
import com.hsytech.dijiebao.utils.Constants;
import com.hsytech.dijiebao.utils.HttpUtil;
import com.hsytech.dijiebao.utils.SharedPreferencesTools;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import cn.jpush.android.api.JPushInterface;

public class SeeCityActivity extends BaseActivity {
    public static String Def_cityName = "Def_city";
    private ImageButton top_back_btn;
    private Button bar_right_top_btn;
    private TextView bar_title_tv, finish;
    private SeeCityAdapter sa;
    private List<HashMap<String, Object>> listData = new ArrayList<HashMap<String, Object>>();
    private ListView city_list;
    private CheckBox check_box;
    private SeeCityBean scb;
    private String c1;
    private List<SeeCityBean> cl = new ArrayList<SeeCityBean>();
    private HashMap<String, Object> hashMap;
    private HashMap<String, String> mCheckedData = new HashMap<String, String>();
    private HashMap<String, String> mCheckedName = new HashMap<String, String>();
    private String[] baseCityIds, baseCityNames;
    private String httpDef_city;
    private String httpDef_cityName;
    private StringBuffer stringBuilder, stringBuilderName;
    private int childrenLength = 0;

    private DPHttpUtil.HttpCallback callBack = new DPHttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, String response) {
            getCityID();
            JSONObject result = null;
            try {
                result = new JSONObject(response);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            JSONArray list = result.optJSONArray("list");

            httpDef_city = result.optString("def_city");

            for (int i = 0; i < list.length(); i++) {
                hashMap = new HashMap<String, Object>();
                JSONArray children = list.optJSONObject(i).optJSONArray("children");
                String areaName = list.optJSONObject(i).optString("name");
                hashMap.put("city1", areaName);
                hashMap.put("type", 0);
                hashMap.put("checked", false);
                listData.add(hashMap);

                childrenLength = childrenLength + children.length();

                for (int j = 0; j < children.length(); j++) {

                    hashMap = new HashMap<String, Object>();

                    String httpCityName = children.optJSONObject(j).optString("name");

                    String httpCityID = children.optJSONObject(j).optString("id");

                    // int cityID = children.optJSONObject(j).optInt("id");

                    hashMap.put("type", 1);

                    hashMap.put("city", httpCityName);

                    hashMap.put("id", httpCityID);

                    hashMap.put("checked", false);

                    if (baseCityIds != null) {

                        for (int a = 0; a < baseCityIds.length; a++) {

                            String baseID = baseCityIds[a];

                            if (baseID.equals(httpCityID)) {

                                hashMap.put("checked", true);

                                break;

                            } else {

                                hashMap.put("checked", false);

                            }

                        }

                    }
                    listData.add(hashMap);

                }
            }
            bar_right_top_btn.setVisibility(View.VISIBLE);
            if (baseCityIds == null) {
                bar_right_top_btn.setText("全选");

            } else {
                if (baseCityIds.length == childrenLength) {
                    bar_right_top_btn.setText("取消全选");
                }else {
                    bar_right_top_btn.setText("全选");
                }
            }
            sa.notifyDataSetChanged();
        }

        @Override
        public void onError(int what, int type, VolleyError error) {

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_see_city);
        initTitle();
        getHttp();
        initView();
    }

    private void getCityID() {
        String cityID = SharedPreferencesTools.getCityID(SeeCityActivity.this);
        String cityName = SharedPreferencesTools.getCityName(SeeCityActivity.this);
        if (cityID != null && cityName != null && !cityID.equals("") && !cityName.equals("")) {
            baseCityIds = cityID.split(",");
            baseCityNames = cityName.split(",");
            for (int i = 0; i < baseCityIds.length; i++) {
                mCheckedData.put(baseCityIds[i], baseCityIds[i]);
                mCheckedName.put(baseCityNames[i], baseCityNames[i]);

            }
        } else {
            // mCheckedData.put(httpDef_city, httpDef_city);
            // mCheckedName.put(httpDef_cityName, httpDef_cityName);
        }
        // }

    }

    private void initView() {
        city_list = (ListView) findViewById(R.id.city_list);
        city_list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                Map<String, Object> data = listData.get(position);
                if (data.get("type").equals("0")) {

                } else {

                    boolean checked = (Boolean) data.get("checked");

                    String id = (String) data.get("id");
                    String name = (String) data.get("city");
                    if (checked) {
                        if (mCheckedData.containsKey(id)) {
                            mCheckedData.remove(id);
                            mCheckedName.remove(name);
                        }
                    } else {
                        mCheckedData.put(id, id);
                        mCheckedName.put(name, name);
                    }
                    ImageView itemImage = (ImageView) arg1.findViewById(R.id.check_box);
                    itemImage.setImageResource(checked ? R.mipmap.gary_no : R.mipmap.blue_yes);
                    listData.get(position).put("checked", !checked);

                    if (mCheckedData.size() == childrenLength) {
                        bar_right_top_btn.setText("取消全选");
                    } else {
                        bar_right_top_btn.setText("全选");
                    }
                }

            }
        });

        sa = new SeeCityAdapter(this, listData);
        city_list.setAdapter(sa);

        finish = (TextView) findViewById(R.id.finish);
        finish.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                stringBuilder = new StringBuffer();
                if (!mCheckedData.isEmpty()) {

                    // if (!mCheckedData.containsKey(12)) {
                    // mCheckedData.put("12", "12");
                    // }
                    for (String key : mCheckedData.keySet()) {

                        stringBuilder.append(key);
                        stringBuilder.append(",");
                    }

                    stringBuilder = stringBuilder.delete(stringBuilder.length() - 1, stringBuilder.length());
                }

                stringBuilderName = new StringBuffer();
                if (!mCheckedName.isEmpty()) {

                    for (String key : mCheckedName.keySet()) {
                        stringBuilderName.append(key);
                        stringBuilderName.append(",");
                    }
                    stringBuilderName = stringBuilderName.delete(stringBuilderName.length() - 1,
                            stringBuilderName.length());
                }
                SharedPreferencesTools.writeCityName(SeeCityActivity.this, String.valueOf(stringBuilderName));
                Log.d("mylog", stringBuilderName.length() + "stringBuilderName");
                SharedPreferencesTools.writeCityID(SeeCityActivity.this, String.valueOf(stringBuilder));
                DPLogUtil.d("保存到本地 cityname=" + stringBuilderName);
                DPLogUtil.d("保存到本地 cityId=" + stringBuilder);


                Set<String> set = new HashSet<String>();
                String[] baseCityName = null;
                String cityName = SharedPreferencesTools.getCityName(getApplicationContext());
                Log.d("mylog", cityName + "==cityName");
                if (cityName != null && !cityName.equals("")) {
                    baseCityName = cityName.split(",");
                    Log.d("mylog", baseCityName.length + "==baseCityName");
                    for (int i = 0; i < baseCityName.length; i++) {
                        set.add(baseCityName[i]);
                    }
                    Log.d("mylog", set.size() + "==for");
                }
                if (set != null) {
                    Log.d("mylog", set.size() + "setset");
                    JPushInterface.setTags(getApplicationContext(), set, null);
                }
                finish();
            }
        });

    }

    private void initTitle() {
        top_back_btn = (ImageButton) findViewById(R.id.top_back_btn);
        top_back_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        bar_right_top_btn = (Button) findViewById(R.id.bar_right_top_btn);
        bar_right_top_btn.setVisibility(View.GONE);
        bar_right_top_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (bar_right_top_btn.getText().toString().equals("全选")) {
                    sa.setSelected(true);
                    bar_right_top_btn.setText("取消全选");

                    for (int i = 0; i < listData.size(); i++) {
                        HashMap<String, Object> map = listData.get(i);
                        if (map != null) {
                            int viewType = sa.getItemViewType(i);
                            if (viewType == 0) {

                            } else {
                                mCheckedData.put((String) map.get("id"), (String) map.get("id"));
                                mCheckedName.put((String) map.get("city"), (String) map.get("city"));
                            }
                        }
                    }


                } else {
                    sa.setSelected(false);
                    bar_right_top_btn.setText("全选");
                    mCheckedData.clear();
                    mCheckedName.clear();
                }

            }
        });
        bar_title_tv = (TextView) findViewById(R.id.bar_title_tv);
        bar_title_tv.setText("关注城市");
    }

    private void getHttp() {

        HttpUtil.httpGet(this, 0, Constants.HTTP_SEE_CITY, callBack);

    }


}
